//
//  RBNetworkTool.m
//  RMMaterialRed
//
//  Created by XBWH on 2024/3/6.
//

#import "RBNetworkTool.h"
#import "RBAESTool.h"
#import "QiniuSDK.h"
#import <AssetsLibrary/AssetsLibrary.h>

@implementation RBNetworkTool
+(NSString *)rb_formatUrl:(NSString *)url{
    if (![url containsString:@"https://"]) {
        return [NSString stringWithFormat:@"%@",url];
    } else {
        return url;
    }
}
+(NSDictionary *)rb_formatParams:(NSDictionary *)params{
    NSMutableDictionary *dict;
    if (params == nil) {
        dict = [[NSMutableDictionary alloc] init];
    } else {
        if ([params isKindOfClass:[NSDictionary class]]) {
            dict = [[NSMutableDictionary alloc] initWithDictionary:params];
        } else {
            dict = [[NSMutableDictionary alloc] init];
        }
    }
    [RBHttpNetworkHelper setAFHTTPSessionManagerProperty:^(AFHTTPSessionManager *sessionManager) {
        sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/plain", @"text/html",
                                                                    @"text/javascript", @"image/*", @"application/json;charset=utf-8",
                                                                    @"application/x-www-form-urlencoded; charset=utf-8", nil];
    }];
    [RBHttpNetworkHelper setRequestSerializer:RBRequestSerializerJSON];
    [RBHttpNetworkHelper setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    [RBHttpNetworkHelper setValue:[[UIDevice currentDevice] systemVersion] forHTTPHeaderField:@"mobileSystem"];
    [RBHttpNetworkHelper setValue:[RBTool rb_getMobileType] forHTTPHeaderField:@"moblieType"];
    [RBHttpNetworkHelper setValue:@"1" forHTTPHeaderField:@"encrypt"];
    [RBHttpNetworkHelper setValue:@"IOS" forHTTPHeaderField:@"client"];
    NSString *auditStatus = [[NSUserDefaults standardUserDefaults]objectForKey:@"auditStatus"];
    [RBHttpNetworkHelper setValue:[NSString stringWithFormat:@"%@",auditStatus] forHTTPHeaderField:@"auditStatus"];
    [RBHttpNetworkHelper setValue:@"user" forHTTPHeaderField:@"term"];
    [RBHttpNetworkHelper setValue:[RBTool rb_getuuid] forHTTPHeaderField:@"uuid"];
    [RBHttpNetworkHelper setValue:[RBTool rb_getCurrentVersion] forHTTPHeaderField:@"version"];
    if ([RBArchiveTool isLogin]) {//登录
        NSString *loginToken = [RBArchiveTool rb_userModel].token;
        [RBHttpNetworkHelper setValue:loginToken forHTTPHeaderField:@"X-Access-Token"];
    }
    return dict;
}
+(void)rb_formatResponseData:(id)response WithURL:(NSString *)url WithParams:(NSDictionary *)params WithSuccess:(RBHttpRequestSuccess)success WithError:(RBHttpRequestError)error{
    NSString *result = response[@"result"];
    
    if ([response[@"success"] intValue]==1&&![response[@"result"] isEqual:[NSNull class]]&&result.length>0&&![RBTool rb_isEmptyStr:result]){
        
        NSMutableDictionary *formatDict = [NSMutableDictionary dictionary];
        NSDictionary *formatResponse = response;
        formatDict = formatResponse.mutableCopy;
        NSString *resultStr = [RBAESTool rb_dswy_decryptStringWithString:formatDict[@"result"]];
        resultStr = [resultStr stringByReplacingOccurrencesOfString:@"\0" withString:@""];
        if([resultStr isEqualToString:@"\"\""]){
            [formatDict setObject:@" " forKey:@"result"];
        }else{
            NSData *jsonData = [resultStr dataUsingEncoding:NSUTF8StringEncoding];
            NSError *error;
            id jsonStr = [NSJSONSerialization JSONObjectWithData:jsonData
                                                         options:NSJSONReadingMutableContainers
                                                           error:&error];
            if(error){
                if([resultStr isEqualToString:@"true"]){
                    jsonStr = @"1";
                }else if([resultStr isEqualToString:@"false"]){
                    jsonStr = @"0";
                }else{
                    if (!RBStringIsEmpty(resultStr)) {
                        jsonStr = resultStr;
                    } else {
                        jsonStr = @"";
                    }
                }
            }
            [formatDict setObject:jsonStr forKey:@"result"];
            if([url containsString:@"userRechargeRecord/createOrder"] && [params[@"payChannel"] isEqualToString:@"ALI_APP"]){
                [formatDict setObject:response[@"message"] forKey:@"result"];
            }
        }
        response = formatDict.mutableCopy;
    }else{
        NSMutableDictionary *formatDict = [NSMutableDictionary dictionary];
        NSDictionary *formatResponse = response;
        formatDict = formatResponse.mutableCopy;
        NSDictionary *dict = [NSDictionary dictionary];
        [formatDict setObject:dict forKey:@"result"];
        response = formatDict.mutableCopy;
    }
    
    if ([response[@"success"] intValue] == 1) {
        if ([response isKindOfClass:[NSData class]]) {
            response = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableContainers error:nil];
        }
        success(response);
    } else {
        if ([response[@"success"] intValue] != 1) {
            if ([response isKindOfClass:[NSData class]]) {
                response = [NSJSONSerialization JSONObjectWithData:response
                                                           options:NSJSONReadingMutableContainers
                                                             error:nil];
            }
            if ([((NSDictionary *)response).allKeys containsObject:@"message"]) {
                NSString *msg = response[@"message"];
                if (msg && [msg isKindOfClass:[NSString class]] && msg.length) {
                    // 单独对某一个错误提示信息处理
                    if ([url containsString:@"appUser/queryUserReceiveCoupon"]||[url containsString:@"api/appUser/queryHomePagePopup"]) {
                    }else{
                        [MBProgressHUD rb_showAutoMessage:msg ToView:RBWindow];
                    }
                }else {
                    if ([((NSDictionary *)response).allKeys containsObject:@"error"]) {
                        NSArray *errorArr = response[@"error"];
                        if (errorArr && [errorArr isKindOfClass:[NSArray class]] && errorArr.count) {
                            [MBProgressHUD rb_showAutoMessage:errorArr[0][@"location"] ToView:RBWindow];
                        }
                    }
                }
            }
        }
        error(response);
    }
}
+(void)rb_formatFailed:(id)error WithUrl:(NSString *)url WithParams:(NSDictionary *)params failed:(RBHttpRequestFailed)failed{
    failed(error);
}
///GET请求,无缓存
+ (__kindof NSURLSessionTask *)GET:(NSString *)URL
                        parameters:(id)parameters
                           success:(RBHttpRequestSuccess)success
                             error:(RBHttpRequestError)error
                           failure:(RBHttpRequestFailed)failure
{
    NSURLSessionTask *task = [RBHttpNetworkHelper GET:[self rb_formatUrl:URL]
                                           parameters:[self rb_formatParams:parameters]
                                              success:^(id responseObject) {
        [self rb_formatResponseData:responseObject WithURL:[self rb_formatUrl:URL] WithParams:parameters WithSuccess:success WithError:error];
    }failure:^(NSError *error) {
        [self rb_formatFailed:error WithUrl:URL WithParams:parameters failed:failure];
    }];
    return task;
}
///POST请求,无缓存
+ (__kindof NSURLSessionTask *)POST:(NSString *)URL
                         parameters:(id)parameters
                            success:(RBHttpRequestSuccess)success
                              error:(RBHttpRequestError)error
                            failure:(RBHttpRequestFailed)failure
{
    NSURLSessionTask *task = [RBHttpNetworkHelper POST:[self rb_formatUrl:URL]
                                            parameters:[self rb_formatParams:parameters]
                                               success:^(id responseObject) {
        [self rb_formatResponseData:responseObject WithURL:[self rb_formatUrl:URL] WithParams:[self rb_formatParams:parameters] WithSuccess:success WithError:error];
    }failure:^(NSError *error) {
        [self rb_formatFailed:error WithUrl:URL WithParams:parameters failed:failure];
    }];
    return task;
}
@end
